<?php
/**
 *  自动注册
 */
class Register extends RegisterBase
{
	public $validateToken = false;

	public function logic()
	{
		//是否有存在的账号
		$uid = $this->checkExistsUser($this->params['imei'], $this->params['mac']);
		if ($uid > 0){
			$newUser = $this->getUser($uid);
		}

		//如果没有已存在的账号，则创建
		if (empty($newUser)) {
			$userInfo = $this->createUser();
			$this->afterRegister($userInfo);
			$newUser  = $this->getExtraInfo($userInfo);
			$newUser  = $this->afterUserInfo($newUser);
		}

		//注册失败
		if ($newUser) {
			$newUser = $this->formatNumber($newUser);
			$this->afterLogin($newUser);
			$this->returnData('suc_register', $newUser);
		} else {
			$this->returnError('failed_login');
		}
	}

	/**
	 * 判断imei,mac是否已注册
	 * @param $imei
	 * @param $mac
	 * @return int
	 */
	public function checkExistsUser($imei, $mac)
	{
		$uid = 0;
		$key = "I:" . $imei . str_replace(":", "", $mac);

		if ($this->userRedis->exists($key)) {
			$userToImei = $this->userRedis->hMget($key, array("uid"));
			$uid = $userToImei["uid"];
		}

		return $uid;
	}

	/**
	 * 创建用户
	 * @return array
	 */
	public function createUser()
	{
		$userInfo = $this->getUserInfo();
		//开始事务
		$this->userRedis->multi();

		$result = $this->createNewUser($userInfo);
		if ($result) {
			//生成UID和imei,mac匹配关系
			$userToImei = $this->params['imei'] . str_replace(":", "", $this->params['mac']);
			$arr = array("uid" => $userInfo['uid']);
			$result = $this->userRedis->hMset("I:$userToImei", $arr);
		}

		if ($result){
			//提交事务
			$this->userRedis->exec();
			return $userInfo;
		}

		//撤消事务
		$this->userRedis->discard();
		$this->returnError("failed_redis_act");
	}
}
?>